package com.huan.service.impl;


import com.huan.dao.mapper.TeachMapper;
import com.huan.pojo.PageBean;

import com.huan.pojo.Teach;
import com.huan.service.TeachService;
import com.huan.util.SqlSessionFactoryUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import java.util.List;


public class TeachServiceImpl implements TeachService {
    //1.创建工厂对象
    SqlSessionFactory factory = SqlSessionFactoryUtils.getSqlSessionFactory();


    @Override
    public PageBean<Teach> selectByPageAndCondition(int currentPage, int pageSize, Teach teach) {
        SqlSession sqlSession = factory.openSession();
        TeachMapper mapper = sqlSession.getMapper(TeachMapper.class);

        //计算开始索引
        int begin = (currentPage - 1)*pageSize;
        //计算查询条目数
        int size = pageSize;


        //查询当前页数据
        List<Teach> rows = mapper.selectByPageAndCondition(begin, size, teach);

        //查询总记录数
        int totalCount = mapper.selectTotalCountByCondition(teach);

        //封装PageBean对象
        PageBean<Teach> pageBean = new PageBean<>();
        pageBean.setRows(rows);
        pageBean.setTotalCount(totalCount);

        sqlSession.close();

        return pageBean;
    }

    @Override
    public boolean add(Teach teach) {
        SqlSession sqlSession = factory.openSession();
        TeachMapper mapper = sqlSession.getMapper(TeachMapper.class);
        boolean flag = mapper.add(teach);
        sqlSession.commit();
        sqlSession.close();
        return flag;
    }

    @Override
    public int update(Teach teach) {
        SqlSession sqlSession = factory.openSession();
        TeachMapper mapper = sqlSession.getMapper(TeachMapper.class);
        int i = mapper.update(teach);
        sqlSession.commit();
        sqlSession.close();
        return i;
    }

    @Override
    public void delete(String teacherID, String courseID) {
        SqlSession sqlSession = factory.openSession();
        TeachMapper mapper = sqlSession.getMapper(TeachMapper.class);
        mapper.delete(teacherID,courseID);
        sqlSession.commit();
        sqlSession.close();
    }
}
